/*
 * @Author: fisher
 * @Date: 2024-03-04 11:15:07
 * @LastEditors: fisher luthor-li@qq.com
 * @LastEditTime: 2024-03-04 16:16:22
 * @FilePath: \allback\services\wsService.js
 * @Description:
 */
const WebSocket = require('ws')

let wss

// 初始化 WebSocket 服务
function initWebSocketServer(server) {
  wss = new WebSocket.Server({ server, path: '/appMsg' })
  setupConnectionHandling()
}

// 设置连接处理逻辑
function setupConnectionHandling() {
  wss.on('connection', ws => {
    console.log('WebSocket connection established.')

    ws.on('message', message => {
      console.log('Received message from client:', message)
    })

    ws.on('close', () => {
      console.log('WebSocket connection closed.')
    })
  })
}

// 广播消息到所有连接的客户端
function broadcastMessage(data) {
  if (!wss) {
    throw new Error('WebSocket server has not been initialized.')
  }

  wss.clients.forEach(client => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(JSON.stringify(data))
    }
  })
}

module.exports = { initWebSocketServer, broadcastMessage }
